#!/usr/bin/env php
<?php

// echo "load boostrap/app.php.... <br/>";


use Core\Framework\Console\Input\InputArgv;

$application = require_once __DIR__.'/boostrap/app.php';

// load the task register file...
$registerFile = __DIR__ . '/app/Console/Register.php';
$taskRegisters = [];
if(file_exists($registerFile)) {
    $taskRegisters = require_once __DIR__ . '/app/Console/Register.php';
}


function PrintLog($message)
{
    echo $message . PHP_EOL;
}


$exitCode = 0;

try {
    // parse the arguments
    $input = new InputArgv();

    //
    $allRegisterJobs = $taskRegisters['jobs'];

    PrintLog("All register jobs:" . print_r($allRegisterJobs, true));

    // command line.....
    $firstParams = $input->getFirstArgument();

    PrintLog("First Params --> " . $firstParams);


    $argums = $input->getOptions();

    PrintLog("All arguments: " . print_r($argums, true));

    $uuid = $input->getOption("uuid");
    PrintLog("UUID: " . $uuid);


    if(array_key_exists($firstParams, $allRegisterJobs)) {
        // find the command
        $arguments = [
            'uuid' =>  $input->getOption("uuid"),
            'parameter' => $input->getOption("parameter"),
            'action' => $input->getOption("action")
        ];

        $className = $allRegisterJobs[$firstParams];

        // construct task object.
        $object = new $className();

        if($object) {
            // run the task
            $object->handle($arguments);
        }


    } else {
        if($firstParams === 'run') {
            // run some commands. for example: --help or --version
        }
    }

    $exitCode = 1;
} catch (\Exception $e) {

    PrintLog($e->getMessage());

    $exitCode = $e->getCode();
    if (is_numeric($exitCode)) {
        $exitCode = (int) $exitCode;
        if (0 === $exitCode) {
            $exitCode = 1;
        }
    } else {
        $exitCode = 1;
    }
} finally {
    // if the exception handler changed, keep it
    // otherwise, unregister $renderException

}

if ($exitCode > 255) {
    $exitCode = 255;
}

exit($exitCode);

